﻿#include "Primitive.h"

Primitive::Primitive()
    :_buffersVAO(0)
{
    // 申请vaoId
    glGenVertexArrays(1, &_buffersVAO);
}

Primitive::~Primitive()
{
    if (glIsVertexArray(_buffersVAO))
    {
        // 删除VAO
        glDeleteVertexArrays(1, &_buffersVAO);
    }
}

void Primitive::reload()
{
    // 绑定vao
    glBindVertexArray(_buffersVAO);

    if (_vertexData)
    {
        _vertexData->use();
    }

    if (_indexBuffer)
    {
        _indexBuffer->use();
    }

    if (_matrixBuffer)
    {
        _matrixBuffer->use();
    }

    if (_textureData)
    {
        _textureData->use();
    }

    // 恢复vao
    glBindVertexArray(0);
}

void Primitive::draw()
{
    if (!_program || !_indexBuffer)
    {
        return;
    }

    _program->use();
    glBindVertexArray(_buffersVAO);
    // 渲染图形:图元类型、索引数量、索引数据类型、索引数据指针(传空则从GPU缓冲区中读取)
    glDrawElementsInstanced(GL_TRIANGLES, _indexBuffer->getIndexNumber(), GL_UNSIGNED_INT, (const void*)0, 1);
    glBindVertexArray(0);
}

GLuint Primitive::getVAO() const
{
    return _buffersVAO;
}
